package com.geetour.columbus.core.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter {

    public static final String    SESSION_LOGINUSER = "sessionLoginUser";
    protected static final String SUFFIX            = "suffix";

    protected FilterConfig        filterConfig      = null;
    protected boolean             ignore            = true;
    protected String[]            suffixArray;

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
                                                                                    ServletException {
        //选择URL进行拦截
        this.chooseUrl(req, res);
        chain.doFilter(req, res);
    }
    
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        String suffix = filterConfig.getInitParameter(SUFFIX);
        suffixArray = suffix.split(",");
    }
    
    /**
     * 选择URL进行拦截
     * @param req
     * @param res
     * @throws IOException
     */
    private void chooseUrl(ServletRequest req, ServletResponse res) throws IOException{
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession();
        String url = request.getRequestURI();
        if (url == null) {
            response.sendRedirect("/toLogin.jsp");
        } else {
            if (!(url.equals("/toLogin.jsp") || url.equals("/login.jsp"))) {
                if (this.hasSuffix(url)) {
                    Object userObj = session.getAttribute(SESSION_LOGINUSER);
                    if (userObj == null) {
                        response.sendRedirect("/toLogin.jsp");
                    }
                } 
            }
        }
    }
    
    /**
     * 判断是否含有被拦截后缀
     * @param url
     * @return
     */
    private boolean hasSuffix(String url) {
        boolean hasSuffix = false;
        for (String suf : suffixArray) {
            hasSuffix = url.endsWith(suf);
            if (hasSuffix) {
                break;
            }
        }
        return hasSuffix;
    }

}
